﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using Webdiyer.WebControls.Mvc;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.EFDBFirst;
using YiYiTong.Rocket.Model;
using System.ComponentModel;
using YiYiTong.Rocket.Model.Manager;
using YiYiTong.Rocket.Business;

namespace YiYiTong.Rocket.ManageWeb.Controllers
{
    public class FinanceController : BaseController
    {
        [Description("销售列表")]
        [ViewPage]
        public ActionResult SaleList(SaleListQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            //条件筛选
            var queryable = dbcontext.View_SaleSettlement.GroupBy(t => new { t.sale_date }).Select(t => new SaleListModel
            {
                sale_date = t.Key.sale_date,
                sale_money = t.Sum(a => a.sale_money),
                buyer_money = t.Sum(a => a.buyer_money),
                recommend_money = t.Sum(a => a.recommend_money),
            });
            if (queryModel.beg_time.HasValue)
                queryable = queryable.Where(t => t.sale_date >= queryModel.beg_time);
            if (queryModel.end_time.HasValue)
            {
                var end_time = queryModel.end_time.Value.AddDays(1);
                queryable = queryable.Where(t => t.sale_date < end_time);
            }

            //分页
            int rowcounts = queryable.Count();
            ViewData.Add("AllCount", rowcounts);
            var sum_salemoney = queryable.Sum(t => t.sale_money);
            var sum_buyermoney = queryable.Sum(t => t.buyer_money);
            var sum_recommendmoney = queryable.Sum(t => t.recommend_money);
            ViewData.Add("AllSaleMoney", sum_salemoney);
            ViewData.Add("AllBuyerMoney", sum_buyermoney);
            ViewData.Add("AllRecommendMoney", sum_recommendmoney);
            var querylist = queryable.OrderByDescending(t => t.sale_date)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            PagedList<SaleListModel> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<SaleListModel>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }

        [Description("销售结算明细")]
        [ViewPage]
        public ActionResult SaleSettlementList(SaleSettleListQueryModel queryModel)
        {
            ViewBag.paramModel = queryModel;

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            //条件筛选
            var queryable = dbcontext.View_SaleSettlement.Where(t => (t.buyer_money.Value + t.recommend_money.Value) > 0);
            if (!string.IsNullOrWhiteSpace(queryModel.account_mobile))
                queryable = queryable.Where(t => t.account_mobile == queryModel.account_mobile);
            if (!string.IsNullOrWhiteSpace(queryModel.member_name))
                queryable = queryable.Where(t => t.member_name.Contains(queryModel.member_name));
            if (!string.IsNullOrWhiteSpace(queryModel.replace_buyer_NO))
                queryable = queryable.Where(t => t.replace_buyer_NO == queryModel.replace_buyer_NO);
            if (queryModel.is_settled != -10)
                queryable = queryable.Where(t => t.is_settled == queryModel.is_settled);
            if (queryModel.beg_time.HasValue)
                queryable = queryable.Where(t => t.sale_date >= queryModel.beg_time);
            if (queryModel.end_time.HasValue)
            {
                var end_time = queryModel.end_time.Value.AddDays(1);
                queryable = queryable.Where(t => t.sale_date < end_time);
            }

            //分页
            int rowcounts = queryable.Count();
            ViewData.Add("AllCount", rowcounts);
            var sum_salemoney = queryable.Sum(t => t.sale_money);
            var sum_buyermoney = queryable.Sum(t => t.buyer_money);
            var sum_recommendmoney = queryable.Sum(t => t.recommend_money);
            ViewData.Add("AllSaleMoney", sum_salemoney);
            ViewData.Add("AllBuyerMoney", sum_buyermoney);
            ViewData.Add("AllRecommendMoney", sum_recommendmoney);
            var querylist = queryable.OrderByDescending(t => t.sale_date).ThenByDescending(t => t.replace_buyer_NO)
                .Skip(queryModel.pageSize * (queryModel.pageIndex - 1))
                .Take(queryModel.pageSize)
                .ToList();

            PagedList<View_SaleSettlement> pagedlist = null;
            if (querylist != null && querylist.Count != 0)
                pagedlist = new PagedList<View_SaleSettlement>(querylist, queryModel.pageIndex, queryModel.pageSize, rowcounts);
            return View(pagedlist);
        }
        [Description("销售结算详情")]
        [NoVerify]
        [ViewPage]
        public ActionResult salesettlementinfo(string date,long uid)
        {
            ViewBag.date = date;
            ViewBag.uid = uid;
            return View();
        }


        [Description("销售结算")]
        [HttpPost]
        public ActionResult toSettlement(long id = 0)
        {
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.IsSuccess = false;
            resMsg.Message = "操作失败";

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var entity = dbcontext.ADZ_SaleSettlement.FirstOrDefault(t => t.seq_id == id);
            if (entity != null)
            {
                entity.is_settled = 1;
                entity.settlement_time = DateTime.Now;
                if (dbcontext.SaveChanges() > 0)
                {
                    resMsg.IsSuccess = true;
                    resMsg.Message = "操作成功";
                }

                //给账户增加余额
                var chargeMember = dbcontext.ADZ_ChargeMaster.FirstOrDefault(t => t.uid == entity.uid);
                if (chargeMember != null)
                {
                    decimal buyer_money = 0, recommend_money = 0;
                    if (entity.buyer_money.HasValue && entity.buyer_money.Value > 0)
                    {
                        buyer_money = entity.buyer_money.Value;
                        AccountBiz.Instance.AddAmountLog((long)chargeMember.uid, (decimal)entity.buyer_money.Value, (int)OrderType.PerformanceSettlement, entity.seq_id.ToString(), 0, entity.sale_date.ToString(2) + "服务费结算", "服务费结算", 0);
                    }
                    if (entity.recommend_money.HasValue && entity.recommend_money.Value > 0)
                    {
                        recommend_money = entity.recommend_money.Value;
                        AccountBiz.Instance.AddAmountLog((long)chargeMember.uid, (decimal)entity.recommend_money.Value, (int)OrderType.RecommendSettlement, entity.seq_id.ToString(), 0, entity.sale_date.ToString(2) + "推荐费结算", "推荐费结算", 0);
                    }
                    chargeMember.account_balance += buyer_money + recommend_money;
                    dbcontext.SaveChanges();
                }
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }

        [Description("批量结算")]
        [HttpPost]
        public ActionResult toMoreSettlement(string ids)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            ResponseMsg resMsg = new ResponseMsg();
            if (string.IsNullOrWhiteSpace(ids))
            {
                resMsg.IsSuccess = false;
                resMsg.Message = $"传入的信息不对";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            if (ids.EndsWith(","))
                ids = ids.Substring(0, ids.Length - 1);
            StringBuilder strb = new StringBuilder();
            string[] id_arr = Utils.GetStrings(ids, ",");
            foreach (var item in id_arr)
            {
                long seq_id = ConvertHelper.TryPraseInt(item, 0);
                if (seq_id > 0)
                {
                    var entity = dbcontext.ADZ_SaleSettlement.FirstOrDefault(t => t.seq_id == seq_id);
                    if (entity != null)
                    {
                        entity.is_settled = 1;
                        entity.settlement_time = DateTime.Now;

                        //给账户增加余额
                        var chargeMember = dbcontext.ADZ_ChargeMaster.FirstOrDefault(t => t.uid == entity.uid);
                        if (chargeMember != null)
                        {
                            decimal buyer_money = 0, recommend_money = 0;
                            if (entity.buyer_money.HasValue && entity.buyer_money.Value > 0)
                            {
                                buyer_money = entity.buyer_money.Value;
                                AccountBiz.Instance.AddAmountLog((long)chargeMember.uid, (decimal)entity.buyer_money.Value, (int)OrderType.PerformanceSettlement, entity.seq_id.ToString(), 0, entity.sale_date.ToString(2) + "服务费结算", "服务费结算", 0);
                            }
                            if (entity.recommend_money.HasValue && entity.recommend_money.Value > 0)
                            {
                                recommend_money = entity.recommend_money.Value;
                                AccountBiz.Instance.AddAmountLog((long)chargeMember.uid, (decimal)entity.recommend_money.Value, (int)OrderType.RecommendSettlement, entity.seq_id.ToString(), 0, entity.sale_date.ToString(2) + "推荐费结算", "推荐费结算", 0);
                            }
                            chargeMember.account_balance += buyer_money + recommend_money;
                            dbcontext.SaveChanges();
                        }
                    }
                    else
                        strb.Append($"[{seq_id}],");
                }
            }
            dbcontext.SaveChanges();
            if (strb.Length == 0)
            {
                resMsg.IsSuccess = true;
                resMsg.Message = "操作成功";
            }
            else
            {
                resMsg.IsSuccess = false;
                resMsg.Message = string.Format("销售结算明细{0}不存在", strb.ToString());
            }
            return Json(resMsg, JsonRequestBehavior.AllowGet);
        }


        [Description("供应商销售统计")]
        [ViewPage]
        public ActionResult SupplierSaleList(SupplierSaleQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;
            ViewBag.IsShowName = true;
            long supplier_id = -10;

            //获取登录用户名
            string loginName = new CurrentUser().user.loginName;
            Entity.UserInfo managerUser = UserBiz.Instance.GetUserInfo(loginName);
            if (managerUser != null && managerUser.supplier_id > 0)
            {
                supplier_id = managerUser.supplier_id;
                ViewBag.IsShowName = false;
            }
            if (queryModel.supplier_name == null)
                queryModel.supplier_name = "";

            PagedList<OrderBySupplier> pagedlist = null;
            int AllCount = 0;
            decimal AllMoney = 0m;
            var result = OrderBiz.Instance.GetOrderBySupplier(supplier_id, queryModel.supplier_name, queryModel.beg_time.ToString(2), queryModel.end_time.ToString(2), queryModel.pageIndex, queryModel.pageSize);
            if (result.Item1)
            {
                AllCount = result.Item2.allrows;
                AllMoney = result.Item2.allmoney;
                if (result.Item2.list != null && result.Item2.list.Count != 0)
                    pagedlist = new PagedList<OrderBySupplier>(result.Item2.list, queryModel.pageIndex, queryModel.pageSize, result.Item2.allrows);
            }
            ViewData.Add("AllCount", AllCount);
            ViewData.Add("AllMoney", AllMoney);
            return View(pagedlist);
        }

        [Description("商品转发统计")]
        [ViewPage]
        public ActionResult GoodsForwardTongJi(ForwardTongJiQueryModel queryModel)
        {
            queryModel.Trim();
            ViewBag.paramModel = queryModel;

            PagedList<ForwardTongJi> pagedlist = null;
            int AllCount = 0;
            long supplier_id = -10;
            long brand_id = -10;
            long category_id = -10;
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            if (!string.IsNullOrEmpty(queryModel.supplier_name))
            {
                var supplier = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_name == queryModel.supplier_name);
                if (supplier != null)
                    supplier_id = supplier.supplier_id;
            }
            if (!string.IsNullOrEmpty(queryModel.brand_name))
            {
                var brand = dbcontext.ADZ_BrandMaster.FirstOrDefault(t => t.brand_name == queryModel.brand_name);
                if (brand != null)
                    brand_id = brand.brand_id;
            }
            if (!string.IsNullOrEmpty(queryModel.category_name))
            {
                var category = dbcontext.ADZ_GoodsCategory.FirstOrDefault(t => t.category_name == queryModel.category_name);
                if (category != null)
                    category_id = category.category_id;
            }

            var result = GoodsBiz.Instance.ForwardTongJi(supplier_id, brand_id, category_id, queryModel.beg_time.ToString(2), queryModel.end_time.ToString(2), queryModel.pageIndex, queryModel.pageSize);
            if (result.Item1)
            {
                AllCount = result.Item2.allrows;
                if (result.Item2.list != null && result.Item2.list.Count != 0)
                    pagedlist = new PagedList<ForwardTongJi>(result.Item2.list, queryModel.pageIndex, queryModel.pageSize, result.Item2.allrows);
            }
            ViewData.Add("AllCount", AllCount);
            return View(pagedlist);
        }
    }
}